package com.course.servlet;

import com.course.entity.Course;
import com.course.entity.CourseSelection;
import com.course.entity.Student;
import com.course.service.CourseService;
import com.course.service.CourseSelectionService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@WebServlet("/xuesheng_course_records")
public class XueshengCourseRecordsServlet extends HttpServlet {
    private final CourseService courseService = new CourseService();
    private final CourseSelectionService courseSelectionService = new CourseSelectionService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        Student student = (Student) session.getAttribute("student");

        if (student == null) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        List<CourseSelection> studentSelections = courseSelectionService.getStudentCourses(student.getId());
        
        // Create a map of courseId to Course object for easy lookup in JSP
        Map<Integer, Course> courseMap = courseService.getAllCourses().stream()
                .collect(Collectors.toMap(Course::getId, course -> course));

        request.setAttribute("studentSelections", studentSelections);
        request.setAttribute("courseMap", courseMap);
        request.getRequestDispatcher("/student/xuesheng_course_records.jsp").forward(request, response);
    }
} 